import { Button, Card, Form, Checkbox, Select, Input, DatePicker, message, Space, Row, Col } from 'antd';
import { useEffect, useRef, useState } from 'react';
import {
  getusrFamilyInfo,
  putusrFamilyInfo,
} from '@/services/baseinfo'

const FormComponent = () => {
  const [form] = Form.useForm();
  const [componentDisabled, setComponentDisabled] = useState<boolean>(true);//设置组件是否可填
  const [userInfo, setUserInfo] = useState(null); // 用于保存接口返回的家庭信息
  // 定义表单的初始值，根据您的需求设置每个表单字段的初始值
  const initialValues = {
    homeAddress: userInfo?.homeAddress,
    isFinanciallyChallenged: userInfo?.isFinanciallyChallenged,
    isScholarshipApplied: userInfo?.isScholarshipApplied,
  };
  useEffect(() => {
    // 在组件加载时调用接口函数
    fetchData();
  }, []);
  const addButtonRef = useRef(); // 创建一个 useRef 来引用添加家庭成员的按钮
  const [addButtonClicked, setAddButtonClicked] = useState(false); // 创建一个状态来标记按钮是否已点击
  useEffect(() => {
    // 如果 userInfo 存在且有 familyMemberInfos 数据，并且按钮未点击过，则模拟点击两次添加家庭成员的按钮
    if (userInfo && userInfo.familyMemberInfos && !addButtonClicked) {
      addButtonRef.current.click();
      addButtonRef.current.click();
      setAddButtonClicked(true);
    }
  }, [userInfo, addButtonClicked]);
  //获取表单信息接口
  const fetchData = async () => {
    try {
      // 调用接口函数并传递必要的参数
      const response = await getusrFamilyInfo(null, null);
      // 处理返回的数据
      if (response && response.result) {
        setUserInfo(response.result); // 将接口返回的数据保存到状态中
        // console.log(response.result.familyMemberInfos)
      }
    } catch (error) {
      console.error('Error fetching user info:', error);
    }
  };
  const onFinish = (values) => {
    console.log(values);
    putusrFamilyInfo(null, values)
      .then((response) => {
        console.log('API response:', response.code);
        if (response?.code == '200') {
          message.success("提交成功")
          window.location.reload();
        } else message.error("提交失败")
      })
      .catch((error) => {
        console.error('API error:', error);
      });
  };
  if (userInfo === null || userInfo === undefined) {
    return <p>Loading...</p>;
  }
  return (
    <Card >
      <Checkbox
        checked={componentDisabled}
        onChange={(e) => setComponentDisabled(e.target.checked)}
      >
        信息有错?点击更改!
      </Checkbox>
      <Form
        labelCol={{ span: 10 }}
        wrapperCol={{ span: 14 }}
        form={form}
        disabled={componentDisabled}
        initialValues={initialValues} // 设置表单的初始值
        name="control-hooks"
        onFinish={onFinish}
        style={{ maxWidth: 800 }}
      >
        {/* 家庭住址（填写到社区或村门牌号） */}
        <Form.Item
          name="homeAddress"
          label="家庭住址（填写到社区或村门牌号）"
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>
        {/* 是否家庭困难 */}
        <Form.Item
          name="isFinanciallyChallenged"
          label="是否家庭困难"
          rules={[{ required: true }]}
        >
          <Select >
            <Select.Option value="1">是</Select.Option>
            <Select.Option value="0">否</Select.Option>
          </Select>
        </Form.Item>
        {/* 是否申请助学金 */}
        <Form.Item
          name="isScholarshipApplied"
          label="是否申请助学金"
          rules={[{ required: true }]}
        >
          <Select >
            <Select.Option value="1">是</Select.Option>
            <Select.Option value="0">否</Select.Option>
          </Select>
        </Form.Item>

        {/* 在 Form.List 中设置 initialValue 来渲染相应数量的表单项 */}
        <Form.List name="familyMemberInfos" initialValue={userInfo.familyMemberInfos}>
          {(fields, { add, remove }) => (
            <Row gutter={[16, 16]}>
              {fields.map((field, index) => (
                <Col span={24} key={field.key} offset={6}>
                  <Space>
                    <Form.Item
                      label="姓名"
                      name={[field.name, 'parentName']}
                      rules={[{ required: true, message: '请输入姓名' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="关系"
                      name={[field.name, 'parentRelation']}
                      rules={[{ required: true, message: '请输入关系' }]}
                    >
                      <Select>
                        <Select.Option value="0">父子</Select.Option>
                        <Select.Option value="1">父女</Select.Option>
                        <Select.Option value="2">母子</Select.Option>
                        <Select.Option value="3">母女</Select.Option>
                        <Select.Option value="4">兄弟</Select.Option>
                        <Select.Option value="5">姐妹</Select.Option>
                        <Select.Option value="6">兄妹</Select.Option>
                        <Select.Option value="7">姐弟</Select.Option>
                      </Select>
                    </Form.Item>
                    <Form.Item
                      label="电话号码"
                      name={[field.name, 'parentNumber']}
                      rules={[{ required: true, message: '请输入电话号码' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Button onClick={() => remove(field.name)} danger>删除一行</Button>
                  </Space>
                </Col>
              ))}
              <Col span={8}>
                <Button ref={addButtonRef} onClick={() => add()} style={{marginLeft:700}}>添加家庭成员</Button>
              </Col>
            </Row>
          )}
        </Form.List>
        <Button type="primary" htmlType="submit" style={{width:300, marginLeft:400, marginTop:50}}>
          提交
        </Button>
      </Form>
    </Card>
  );
};

export default FormComponent;
